//
//  LGHeartRhythmChartView.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2024/7/31.
//  心律监测 - 统计图

//tag : 1000+:Y轴 、 2000+：虚线 、 3000+：X轴 、 4000+：button
#import "LGHeartRhythmChartView.h"
#import "LGMedicineHistogramLayer.h"
#import "LGScrollView.h"
#define topMargin    viewPix(5)

#define leftMargin   viewPix(45)+iPadMargin(10)

#define lineHeight   viewPix(30)

#define scrollWidth    (Screen_W - viewPix(83))

#define scrollHeight  (lineHeight*5+viewPix(20))

@interface LGHeartRhythmChartView()<UIScrollViewDelegate>
/**   */
@property (nonatomic , strong)LGEmptyView *emptyView;
/**   */
@property (nonatomic , strong)LGScrollView *scrollView;
/**   */
@property (nonatomic , strong)CAShapeLayer *shapeLayer;
/**   */
@property (nonatomic , strong)NSArray *dayArray;
/**   */
@property (nonatomic , strong)NSArray *rightArray;
/**   */
@property (nonatomic , strong)NSArray *warnArray;
/**   */
@property (nonatomic , strong)NSArray *percentArray;
/**   */
@property (nonatomic , strong)NSArray *warnDataArray;
/**   */
@property (nonatomic , assign)NSInteger totalCount;
/**   */
@property (nonatomic , assign)CGFloat itemWidth;
/**   */
@property (nonatomic , strong)NSMutableArray *btnArray;
/**   */
@property (nonatomic , strong)NSMutableArray *layerArray;

@end

@implementation LGHeartRhythmChartView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.itemWidth = scrollWidth/6.0;
        [self createSubView];
    }
    return self;
}

//服药曲线
-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    //计算总宽度
    self.totalCount = [dataDic[@"xAxis"] count]>0?[dataDic[@"xAxis"] count]:1;
    CGFloat totalWidth = viewPix(20)+self.itemWidth*self.totalCount;
    totalWidth = (totalWidth<scrollWidth+viewPix(20))?scrollWidth+viewPix(20):totalWidth;
    self.scrollView.contentSize = CGSizeMake(totalWidth, scrollHeight);
    [self.scrollView setContentOffset:CGPointMake(totalWidth-scrollWidth-viewPix(10), 0)];
    for (NSInteger i=0; i<5; i++){
        LGDottedLineView *lineView = [self viewWithTag:2000+i];
        CGRect rect = lineView.frame;
        lineView.frame = CGRectMake(rect.origin.x, rect.origin.y, totalWidth+viewPix(30), lineHeight);
        [lineView setNeedsDisplay];
    }
    NSInteger count = (self.totalCount>6)?6:self.totalCount;
    self.itemWidth = scrollWidth/count;
    self.warnDataArray = dataDic[@"serieswarnData"];
    self.percentArray = dataDic[@"serieswarnProportion"];
    self.rightArray = dataDic[@"seriesright"];
    self.warnArray = dataDic[@"serieswarn"];
    self.dayArray = dataDic[@"xAxis"];
}

//创建X轴坐标
-(void)setDayArray:(NSArray *)dayArray{
    for (NSInteger i=0; i<self.dayArray.count; i++) {
        UILabel *label = [self viewWithTag:3000+i];
        [label removeFromSuperview];
    }
    for (LGMedicineHistogramLayer *layer in self.layerArray) {
        [layer removeFromSuperlayer];
    }
    
    for (UIButton *button in self.btnArray) {
        [button removeFromSuperview];
    }
    
    if (_shapeLayer) {
        [self.shapeLayer removeFromSuperlayer];
    }
    
    [self.layerArray removeAllObjects];
    [self.btnArray removeAllObjects];
    _dayArray = dayArray;
//    if (dayArray.count == 0) {
//        return;
//    }
    CGFloat maxValue = 0;
    for (NSInteger i=0; i<dayArray.count; i++) {
        UILabel *dayLabel = [UILabel lableWithText:LGNSString(dayArray[i]) colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        dayLabel.frame = CGRectMake(viewPix(10)+self.itemWidth*i, lineHeight*5, self.itemWidth, lineHeight);
        dayLabel.tag = 3000+i;
        [self.scrollView addSubview:dayLabel];
        NSInteger totalCount = [self.rightArray[i] integerValue] + [self.warnArray[i] integerValue];
        maxValue = (maxValue>totalCount)?maxValue:totalCount;
    }
    
    maxValue = maxValue<1?1:maxValue;
    CGFloat marginV = maxValue/4.0;
    for (NSInteger i=0; i<5; i++) {
        UILabel *label = [self viewWithTag:1000+i];
        label.text = [NSString stringWithFormat:@"%.1f",maxValue-marginV*i];
    }
    
    //创建layer
    NSMutableArray *pointArray = [NSMutableArray array];
    for (NSInteger i=0; i<dayArray.count; i++) {
        NSInteger rightCount = [self.rightArray[i] integerValue];
        NSInteger warnCount = [self.warnArray[i] integerValue];
        NSInteger totalCount = rightCount + warnCount;
        CGFloat buttonH = floor((totalCount)/marginV*lineHeight);
        [self createHistogramLayer:i height:buttonH];
        
        //画线 - 占比
        CGFloat value = [self.percentArray[i] floatValue];
        CGFloat pointY = scrollHeight-(value/20.0*lineHeight+viewPix(20)+lineHeight*0.5);
        UIButton *button = [UIButton buttonWithImage:@"心律监测-未选中" selectImage:@"心律监测-选中"];
        button.bounds = CGRectMake(0, 0, viewPix(20), viewPix(20));
        button.center = CGPointMake(viewPix(10)+self.itemWidth/2.0+self.itemWidth*i, pointY);
        button.userInteractionEnabled = NO;
        button.tag = 4000+i;
        [self.scrollView addSubview:button];
        [self.btnArray addObject:button];
        NSValue *point = [NSValue valueWithCGPoint:button.center];
        [pointArray addObject:point];
    }
    [self drawCurveLine:pointArray lineColor:@"#FB670D"];
}

-(void)createHistogramLayer:(NSInteger)index height:(CGFloat)height{
    if(height > 0){
        CGFloat marginY = scrollHeight-height-viewPix(20)-lineHeight/2.0;
        NSInteger totalCount = [self.rightArray[index] integerValue] + [self.warnArray[index] integerValue];
        LGMedicineHistogramLayer *layer = [[LGMedicineHistogramLayer alloc]init];
        layer.frame = CGRectMake(self.itemWidth/2.0+self.itemWidth*index+viewPix(4), marginY, viewPix(12), height);
        layer.percent = [self.warnArray[index] floatValue]/totalCount;
        [self.scrollView.layer addSublayer:layer];
        [self.layerArray addObject:layer];
    }
}

//画线
-(void)drawCurveLine:(NSArray *)arry lineColor:(NSString *)color{
    if(arry.count < 2) return;
    CGPoint startPoint = [[arry objectAtIndex:0] CGPointValue];
    CGPoint lastPoint;
    UIBezierPath *lineBeizer = [UIBezierPath bezierPath];
    [lineBeizer setLineWidth:2.0];
    [lineBeizer moveToPoint:startPoint];

    for (NSInteger i = 0;i < arry.count;i++ ) {
        if (i <arry.count-1 ) {
            CGPoint nowPoint = [[arry objectAtIndex:i] CGPointValue];
            CGPoint futPoint  = [[arry objectAtIndex:i+1] CGPointValue];
            [lineBeizer addCurveToPoint:futPoint controlPoint1:CGPointMake((nowPoint.x+futPoint.x)/2, nowPoint.y) controlPoint2:CGPointMake((nowPoint.x+futPoint.x)/2, futPoint.y)];
            if (i == arry.count-2) {
                [lineBeizer moveToPoint:futPoint];//添加连线
                lastPoint = futPoint;
            }
        }
    }
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = lineBeizer.CGPath;
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.strokeColor = [UIColor colorWithString:color].CGColor;
    shapeLayer.lineWidth = 1.0;
    self.shapeLayer = shapeLayer;
    [self.scrollView.layer addSublayer:shapeLayer];
    for(NSInteger i=0; i<self.totalCount; i++){
        UIButton *button = [self viewWithTag:4000+i];
        [self.scrollView bringSubviewToFront:button];
    }
}

//
-(void)checkRecordDetail:(UITapGestureRecognizer *)sender{
    CGPoint point = [sender locationInView:self.scrollView];
    NSInteger index = ceil((point.x-viewPix(10))/self.itemWidth)-1;
    index = (index<0)?0:index;
    if (index<self.layerArray.count) {
        for (LGMedicineHistogramLayer *layer in self.layerArray) {
            layer.selecte = (layer == self.layerArray[index])?YES:NO;
        }
        for (NSInteger i=0; i<self.btnArray.count; i++) {
            UIButton *button = self.btnArray[i];
            button.selected = (index == i)?YES:NO;
        }
        
        UIButton *button = self.btnArray[index];
        CGPoint btnPoint = [self.scrollView convertPoint:button.center toView:self.superview.superview];
        NSArray *dateArray = [LGNSString(self.dayArray[index]) componentsSeparatedByString:@"/"];
        NSString *dateStr = [NSString stringWithFormat:@"%@月%@日",dateArray[0],dateArray[1]];
        NSDictionary *dic = @{@"right":self.rightArray[index] , @"warn":self.warnArray[index] , @"percent":self.percentArray[index] , @"warnData":self.warnDataArray[index]};
        if(self.delegate && [self.delegate respondsToSelector:@selector(showAlertView:date:point:)]){
            [self.delegate showAlertView:dic date:dateStr point:btnPoint];
        }
    }
    
}


-(void)createSubView{
    [self addSubview:self.scrollView];
    NSArray *titleArray1 = @[@"100%",@"60%",@"40%",@"20%",@"0%"];
    NSArray *titleArray2 = @[@"100",@"60",@"40",@"20",@"0"];
    for (NSInteger i=0; i<titleArray1.count; i++) {
        //Y轴标题-左
        UILabel *label = [UILabel lableWithText:titleArray1[i] colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        label.frame = CGRectMake(0, topMargin+lineHeight*i, leftMargin, lineHeight);
        [self addSubview:label];
        
        //Y轴标题-右
        UILabel *label2 = [UILabel lableWithText:titleArray2[i] colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentLeft lines:1];
        label2.frame = CGRectMake(leftMargin+scrollWidth, topMargin+lineHeight*i, Screen_W-leftMargin-scrollWidth, lineHeight);
        label2.tag = 1000+i;
        [self addSubview:label2];
        
        //虚线
        LGDottedLineView *lineView = [[LGDottedLineView alloc]initWithFrame:CGRectMake(0, lineHeight*i, self.itemWidth*30+viewPix(20), lineHeight)];
        lineView.tag = 2000+i;
        [self.scrollView addSubview:lineView];
    }
    [self addSubview:self.emptyView];
}

-(NSMutableArray *)btnArray{
    if(!_btnArray){
        _btnArray = [NSMutableArray array];
    }
    return _btnArray;
}

-(NSMutableArray *)layerArray{
    if(!_layerArray){
        _layerArray = [NSMutableArray array];
    }
    return _layerArray;
}

-(LGEmptyView *)emptyView{
    if(!_emptyView){
        _emptyView = [[LGEmptyView alloc] initWithFrame:CGRectMake(0, 0, Screen_W-viewPix(32), scrollHeight+topMargin+viewPix(35))];
        _emptyView.backgroundColor = [UIColor colorWithString:@"#FFFFFF"];
        _emptyView.userInteractionEnabled = NO;
        _emptyView.hidden = YES;
    }
    return _emptyView;
}


-(LGScrollView *)scrollView{
    if(!_scrollView){
        _scrollView = [[LGScrollView alloc] initWithFrame:CGRectMake(leftMargin, topMargin, scrollWidth, scrollHeight)];
        _scrollView.contentSize = CGSizeMake(self.itemWidth*30+viewPix(20), scrollHeight);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
        _scrollView.bounces = NO;
        [_scrollView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(checkRecordDetail:)]];
    }
    return _scrollView;
}




@end
